import React, {CSSProperties} from "react"
import {Switch as AntdSwitch} from 'antd'
import {VJsonComponent,} from "../../factory"
import {YvanEvent} from "../../types"
import {apply, YvanEventBind, YvanEventDispatch} from "../../utils/helper"
import {FormItemBaseProp, FormItemBaseState, VJsonFormItemBase} from "./VJsonFormItemBase"
import {toJS} from "mobx";

export interface SwitchVJsonProp extends FormItemBaseProp<Switch> {
    autoFocus?: boolean
    disabled?: boolean;
    size?: 'small' | 'default'
    onChange?: (sender: Switch, value: string, checked: boolean) => void
    onClick?: YvanEvent<Switch>
    className?: string
    style?: CSSProperties

    on?: string,
    off?: string
}

export interface SwitchState extends FormItemBaseState<Switch> {
}

@VJsonComponent({
    view: 'switch'
})
export default class Switch extends VJsonFormItemBase<Switch, SwitchVJsonProp, SwitchState> {
    static defaultProps = {
        ...VJsonFormItemBase.defaultProps,
        on: '1',
        off: '0'
    }

    constructor(props: any) {
        super(props, Switch.defaultProps);
    }

    /**
     * 从控件值到实体 (control -> entity) 的转换 normalizeToEntity
     */
    normalizeToEntity(value: any) {
        if (typeof value === 'boolean') {
            return (value ? this.props.vjson.on : this.props.vjson.off)
        }
        return value
    }

    /**
     * 从实体值到控件 (entity -> control) 的转换 normalizeToEntity
     */
    getCheckedValue(value: any) {
        if (typeof value === 'boolean') {
            return value
        }
        if (value === this.props.vjson.on) {
            return true
        }
        return false
    }

    protected onValueChange(this: any, value: any) {
        this.value = value
        YvanEventDispatch(this.props.vjson.onChange, this, this.normalizeToEntity(value), value)
    }

    protected renderWrapper(): JSX.Element {
        console.log('RenderSwitch ', this.toString())

        return (
            //@ts-ignore
            <AntdSwitch key={this.key} view_id={this.key} aria-roledescription={this.view}
                        autoFocus={apply(this, this.props.vjson.autoFocus)}
                        checked={this.getCheckedValue(this.value)}
                        defaultChecked={apply(this, this.props.vjson.defaultChecked)}
                        disabled={apply(this, this.props.vjson.disabled)}
                        loading={this.loading}
                        size={apply(this, this.props.vjson.size)}
                        onChange={this.onValueChange.bind(this)}
                        onClick={YvanEventBind(this.props.vjson.onClick, this)}
                        className={this.props.vjson.className}
                        style={toJS(this.props.vjson.style)}
            />
        )
    }
}
